package com.gzone.contentprovider.helper;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class BitmapHelper {
	private static final String TBD = "http://91.121.156.153/~services/";
	public static byte[] convertBitmapToByte(Bitmap bmp){
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
		return stream.toByteArray();
	}
	
	public static Bitmap convertByteToBitmap(byte[] img){
		 return BitmapFactory.decodeByteArray(img, 0, img.length);
	}
	
	public static byte[] getByteImageFromURL(String path){
		String url = TBD + path;
		Bitmap bmp = loadBitmap(url);
		if(bmp != null)
			return convertBitmapToByte(bmp);
		return null;
	}
	public static Bitmap loadBitmap(String url)
	{
		Bitmap bm = null;
		InputStream is = null;
		BufferedInputStream bis = null;
		try 
		{
			URLConnection conn = new URL(url).openConnection();
			conn.connect();
			is = conn.getInputStream();
			bis = new BufferedInputStream(is, 8192);
			bm = BitmapFactory.decodeStream(bis);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		finally {
			if (bis != null) 
			{
				try 
				{
					bis.close();
				}
				catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
			if (is != null) 
			{
				try 
				{
					is.close();
				}
				catch (IOException e) 
				{
					e.printStackTrace();
		    			}
		    		}
		    }
		return bm;
	}
}
